/*
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-01-06 18:51:49
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-01-06 18:51:49
 * @FilePath: \HuiLin\utils\simpleTimerCleaner.js
 * @Description: 简单定时器清理工具 - 防止卡死
 */

class SimpleTimerCleaner {
    constructor() {
        this.timers = new Map();
        this.lastCleanupTime = 0;
        this.cleanupInterval = 15000; // 15秒清理一次
    }

    /**
     * 注册定时器
     * @param {string} id 定时器ID
     * @param {number} timer 定时器对象
     */
    registerTimer(id, timer) {
        this.timers.set(id, timer);
        console.log(`[SimpleTimerCleaner] 注册定时器: ${id}`);
    }

    /**
     * 清理定时器
     * @param {string} id 定时器ID
     */
    clearTimer(id) {
        const timer = this.timers.get(id);
        if (timer) {
            clearTimeout(timer);
            clearInterval(timer);
            this.timers.delete(id);
            console.log(`[SimpleTimerCleaner] 清理定时器: ${id}`);
        }
    }

    /**
     * 清理所有定时器
     */
    clearAllTimers() {
        this.timers.forEach((timer, id) => {
            clearTimeout(timer);
            clearInterval(timer);
        });
        this.timers.clear();
        console.log('[SimpleTimerCleaner] 清理所有定时器');
    }

    /**
     * 检查并清理
     */
    checkAndCleanup() {
        const now = Date.now();
        
        // 限制清理频率
        if (now - this.lastCleanupTime < this.cleanupInterval) {
            return;
        }

        const timerCount = this.timers.size;
        
        // 如果定时器数量过多，执行清理
        if (timerCount > 10) {
            console.warn(`[SimpleTimerCleaner] 检测到过多定时器: ${timerCount}，执行清理`);
            this.clearAllTimers();
            this.lastCleanupTime = now;
        }
    }

    /**
     * 获取统计信息
     */
    getStats() {
        return {
            totalTimers: this.timers.size,
            lastCleanupTime: this.lastCleanupTime
        };
    }
}

// 创建单例实例
const simpleTimerCleaner = new SimpleTimerCleaner();

// 定期检查
setInterval(() => {
    simpleTimerCleaner.checkAndCleanup();
}, 10000); // 每10秒检查一次

export default simpleTimerCleaner;
